<template>
  <div class="user-dashboard">
    <!-- 顶部操作栏 -->
    <div class="header">
      <h2>我的车辆</h2>
      <el-button type="primary" @click="addVehicleDialogVisible = true">
        添加车辆
      </el-button>
      <!-- 查询用户所有工单按钮 -->
      <el-button type="info" style="margin-left: 10px" @click="viewAllOrdersDialogVisible = true">
        查询所有工单
      </el-button>
      <el-button type="danger" style="margin-left: 10px" @click="handleLogout">
        退出登录
      </el-button>
    </div>

    <!-- 车辆列表 -->
    <el-card>
      <el-table :data="vehicles" stripe border>
        <el-table-column prop="license_plate" label="车牌号" width="150" />
        <el-table-column prop="model" label="车型" width="180" />
        <el-table-column prop="manufacture_year" label="制造年份" width="120" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleApplyRepair(scope.row)">
              申请维修
            </el-button>
            <el-button type="info" size="small" style="margin-left: 10px" @click="handleViewOrders(scope.row)">
              查看订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加车辆对话框 -->
    <el-dialog v-model="addVehicleDialogVisible" title="添加车辆" width="40%">
      <el-form ref="addVehicleFormRef" :model="addVehicleForm" :rules="addVehicleRules">
        <el-form-item label="车牌号" prop="license_plate">
          <el-input v-model="addVehicleForm.license_plate" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车型" prop="model">
          <el-input v-model="addVehicleForm.model" placeholder="请输入车型（如：奥迪A6）" />
        </el-form-item>
        <el-form-item label="制造年份" prop="manufacture_year">
          <el-input-number v-model="addVehicleForm.manufacture_year" :min="1900" :max="new Date().getFullYear()"
            placeholder="请输入制造年份" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVehicleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddVehicle">提交</el-button>
      </template>
    </el-dialog>

    <!-- 申请维修对话框 -->
    <el-dialog v-model="applyRepairDialogVisible" title="申请维修" width="40%">
      <el-form>
        <el-form-item label="选择维修类型" required>
          <el-checkbox-group v-model="selectedTaskTypes">
            <el-checkbox v-for="type in taskTypes" :key="type" :label="type">
              {{ typeLabelMap[type] }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="applyRepairDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRepairApplication">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查看订单对话框 -->
    <el-dialog v-model="orderDialogVisible" title="车辆订单" width="60%">
      <el-table :data="orders" stripe border>
        <el-table-column prop="order_id" label="订单ID" width="150" />
        <el-table-column label="创建时间" width="200">
          <template #default="scope">
            {{ scope.row.create_time }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">
              {{ scope.row.payment_status ? '已支付' : scope.row.status ? '已完成' : '进行中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前费用" width="120">
          <template #default="scope">
            {{ scope.row.total_cost }} 元
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="pay(scope.row.status, scope.row.order_id)"
              v-if="!scope.row.payment_status" style="margin-left: 8px;">支付</el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看">
          <template #default="scope">
            <el-dropdown trigger="click" placement="bottom-end">
              <el-button type="text" size="small" @click="handleAssignmentsOfOrder(scope.row)">▼</el-button>
              <template #dropdown>
                <el-dropdown-menu style="min-width: 200px;">
                  <div v-if="assignments && assignments.length" style="padding: 12px;">
                    <el-table :data="assignments" border stripe style="width: 100%;">
                      <el-table-column prop="assignment_id" label="任务ID" width="120" align="center">
                        <template #default="scope">
                          任务ID：{{ scope.row?.assignment_id }}
                        </template>
                      </el-table-column>

                      <el-table-column label="执行人" width="180" align="center">
                        <template #default="scope">
                          <span>{{ scope.row?.repair_person_id || '待分配' }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="工种" width="180" align="center">
                        <template #default="scope">
                          <span>{{ typeLabelMap[scope.row?.task_type] || '未知' }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="状态" width="120" align="center">
                        <template #default="scope">
                          <el-tag type="info" size="small">
                            {{ AssignmentStatusMap[scope.row?.status] || '未知状态' }}
                          </el-tag>
                        </template>
                      </el-table-column>

                      <el-table-column label="催单" width="120" align="center">
                        <template #default="scope">
                          <el-button type="primary" size="small" @click="handleRemindRecord(scope.row)">催单</el-button>
                        </template>
                      </el-table-column>

                      <el-table-column label="评分" width="220" align="center">
                        <template #default="scope">
                          <div style="display: flex; align-items: center; justify-content: center; gap: 8px">
                            <el-rate v-model="scope.row.editScore" :max="5" :disabled="scope.row.status !== 'COMPLETED'"
                              :allow-half="false" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" void-color="#C6D1DE"
                              :show-score="false" :score-template="scope.row.score" />
                            <el-button type="primary" size="small"
                              :disabled="scope.row.status !== 'COMPLETED' || !scope.row.editScore"
                              @click="handleScoreSubmit(scope.row)">
                              提交
                            </el-button>
                          </div>
                        </template>
                      </el-table-column>

                    </el-table>
                  </div>
                  <div v-else style="padding: 12px; color: #666;">无分配任务</div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 查询用户所有工单对话框 -->
    <el-dialog v-model="viewAllOrdersDialogVisible" title="用户所有工单" width="80%">
      <el-table :data="allUserOrders" stripe border>
        <el-table-column prop="order_id" label="订单ID" width="150" />
        <el-table-column label="车辆信息" width="250">
          <template #default="scope">
            车牌号: {{ scope.row.vehicle_license_plate }} | 车型: {{ scope.row.vehicle_model }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">
              {{ scope.row.payment_status ? '已支付' : scope.row.status ? '已完成' : '进行中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="pay(scope.row.status, scope.row.order_id)"
              v-if="!scope.row.payment_status" style="margin-left: 8px;">支付</el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看">
          <template #default="scope">
            <el-dropdown trigger="click" placement="bottom-end">
              <el-button type="text" size="small" @click="handleAssignmentsOfOrder(scope.row)">▼</el-button>
              <template #dropdown>
                <el-dropdown-menu style="min-width: 200px;">
                  <div v-if="assignments && assignments.length" style="padding: 12px;">
                    <el-table :data="assignments" border stripe style="width: 100%;">
                      <el-table-column prop="assignment_id" label="任务ID" width="120" align="center">
                        <template #default="scope">
                          任务ID：{{ scope.row?.assignment_id }}
                        </template>
                      </el-table-column>

                      <el-table-column label="执行人" width="180" align="center">
                        <template #default="scope">
                          <span>{{ scope.row?.repair_person_id || '待分配' }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="工种" width="180" align="center">
                        <template #default="scope">
                          <span>{{ typeLabelMap[scope.row?.task_type] || '未知' }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="状态" width="120" align="center">
                        <template #default="scope">
                          <el-tag type="info" size="small">
                            {{ AssignmentStatusMap[scope.row?.status] || '未知状态' }}
                          </el-tag>
                        </template>
                      </el-table-column>

                      <el-table-column label="催单" width="120" align="center">
                        <template #default="scope">
                          <el-button type="primary" size="small" @click="handleRemindRecord(scope.row)">催单</el-button>
                        </template>
                      </el-table-column>

                      <el-table-column label="评分" width="220" align="center">
                        <template #default="scope">
                          <div style="display: flex; align-items: center; justify-content: center; gap: 8px">
                            <el-rate v-model="scope.row.editScore" :max="5" :disabled="scope.row.status !== 'COMPLETED'"
                              :allow-half="false" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" void-color="#C6D1DE"
                              :show-score="false" :score-template="scope.row.score" />
                            <el-button type="primary" size="small"
                              :disabled="scope.row.status !== 'COMPLETED' || !scope.row.editScore"
                              @click="handleScoreSubmit(scope.row)">
                              提交
                            </el-button>
                          </div>
                        </template>
                      </el-table-column>

                    </el-table>
                  </div>
                  <div v-else style="padding: 12px; color: #666;">无分配任务</div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { addVehicleApi, getVehicleByIdApi, getVehiclesApi } from '@/api/vehicle';
import { createOrderApi, getOrdersOfVehicleApi, getAllOrdersByUserApi, payRepairOrderApi, getAssignmentOfOrderApi, commentAssignmentApi, getRemindRecordApi, remindApi } from '@/api/order';
import router from "@/router";

// 从代码库 TaskType 枚举获取维修类型（与后端保持一致）
const taskTypes = ['PAINTER', 'WELDER', 'MECHANIC', 'ELECTRICIAN'];
const typeLabelMap = {
  PAINTER: '漆工',
  WELDER: '焊工',
  MECHANIC: '机修',
  ELECTRICIAN: '电工'
};
const AssignmentStatusMap = {
  PENDING: '待分配',
  ASSIGNED: '已分配',
  IN_PROGRESS: '进行中',
  COMPLETED: '已完成'
}

// 状态管理
const vehicles = ref([]); // 用户车辆列表
const addVehicleDialogVisible = ref(false); // 添加车辆对话框显示状态
const applyRepairDialogVisible = ref(false); // 申请维修对话框显示状态
const orderDialogVisible = ref(false); // 查看订单对话框显示状态
const selectedVehicle = ref(null); // 当前操作的车辆
const selectedTaskTypes = ref([]); // 选择的维修类型
const selectedOrder = ref(null);
const orders = ref([]); // 当前车辆的订单列表
const allUserOrders = ref([]); // 用户所有工单列表
const assignments = ref([]);//当前订单的所有人物列表
const viewAllOrdersDialogVisible = ref(false); // 查询用户所有工单对话框显示状态

// 支付维修订单
const pay = async (status, order_id) => {
  if (!status) {
    ElMessage.warning('订单未完成，无法支付');
    return;
  }
  try {
    const res = await payRepairOrderApi(order_id);
    if (res.data) {
      ElMessage.success('支付成功');
      window.location.reload();
    } else {
      ElMessage.error('支付失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  }
}

// 添加车辆表单
const addVehicleForm = reactive({
  license_plate: '',
  model: '',
  manufacture_year: null,
  user_id: 0
});

const userInfo = localStorage.getItem('userInfo');
const userId = ref(null);
if (userInfo) {
  const parsedUserInfo = JSON.parse(userInfo);
  userId.value = parsedUserInfo.user_id; // 假设用户信息对象中有 id 属性
  console.log('userId:', userId.value);
} else {
  console.log('userInfo 不存在');
}

// 添加车辆表单验证规则
const addVehicleRules = reactive({
  license_plate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入车型', trigger: 'blur' }
  ],
  manufacture_year: [
    { required: true, message: '请输入制造年份', trigger: 'change' },
    { type: 'number', message: '制造年份必须为数字', trigger: 'change' }
  ]
});

const addVehicleFormRef = ref(null);

// 生命周期：加载用户车辆
onMounted(async () => {
  try {
    // 从登录用户信息中获取用户ID（示例：假设用户ID已存储在localStorage）
    const res = await getVehiclesApi(userId.value);
    vehicles.value = res.data;
  } catch (error) {
    ElMessage.error('加载车辆失败，请稍后再试');
  }
});

// 处理添加车辆提交
const submitAddVehicle = async () => {
  await addVehicleFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      addVehicleForm.user_id = userId.value;
      const res = await addVehicleApi(addVehicleForm);
      if (res.data > 0) {
        ElMessage.success('车辆添加成功');
        addVehicleDialogVisible.value = false;
        // 刷新车辆列表
        const newVehicles = await getVehiclesApi(userId.value);
        vehicles.value = newVehicles.data;
        // 清空表单
        addVehicleForm.license_plate = '';
        addVehicleForm.model = '';
        addVehicleForm.manufacture_year = null;
      } else {
        ElMessage.error('车辆添加失败');
      }
    } catch (error) {
      ElMessage.error('网络请求失败');
    }
  });
};

// 处理申请维修（打开对话框并记录当前车辆）
const handleApplyRepair = (vehicle) => {
  selectedVehicle.value = vehicle;
  selectedTaskTypes.value = []; // 清空上次选择
  applyRepairDialogVisible.value = true;
};

// 提交维修申请
const submitRepairApplication = async () => {
  if (selectedTaskTypes.value.length === 0) {
    ElMessage.warning('请至少选择一个维修类型');
    return;
  }
  try {
    // 构造 OrderCreationRequest
    const request = {
      order: {
        user_id: userId.value, // 从登录信息获取用户ID
        vehicle_id: selectedVehicle.value.vehicle_id // 当前车辆ID
      },
      taskTypes: selectedTaskTypes.value // 选择的维修类型列表
    };
    const res = await createOrderApi(request);
    if (res.data > 0) {
      ElMessage.success('维修申请提交成功');
      applyRepairDialogVisible.value = false;
    } else {
      ElMessage.error('维修申请提交失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  }
};

// 处理查看订单（打开对话框并加载车辆订单）
const handleViewOrders = async (vehicle) => {
  selectedVehicle.value = vehicle;
  try {
    const res = await getOrdersOfVehicleApi(vehicle);
    // 对order进行排序，已完成的排在最前面，已支付的排在最后面，其他排在中间
    orders.value = res.data.slice().sort((a, b) => {
      if (a.payment_status && !b.payment_status) {
        return 1; // 已支付的排在最后面
      } else if (a.status && !b.status) {
        return -1; // 已完成的排在最前面
      } else if (!a.status && b.status) {
        return 1;
      } else if (!a.payment_status && b.payment_status) {
        return -1;
      }
      return 0; // 其他保持原顺序
    });
    console.log(orders.value);
    orderDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('加载订单失败');
  }
};

const handleAssignmentsOfOrder = async (order) => {
  selectedOrder.value = order;
  try {
    const res = await getAssignmentOfOrderApi(order.order_id);
    assignments.value = res.data.map(task => ({
      ...task,
      editScore: task.score // 将已存在的评分映射到编辑字段
    }));
    console.log(assignments);
  } catch (error) {
    ElMessage.error('加载任务失败');
  }
}

// 处理查询用户所有工单（打开对话框并加载用户所有工单及其关联车辆信息）
const handleViewAllOrders = async () => {
  try {
    const res = await getAllOrdersByUserApi(userId.value);
    // 假设 getAllOrdersByUserApi 返回的每条工单数据中包含 vehicle_id
    // 我们需要根据 vehicle_id 获取车辆的详细信息
    const orderPromises = res.data.map(async (order) => {
      const vehicleRes = await getVehicleByIdApi(order.vehicle_id) // 假设存在这个API
      return {
        ...order,
        vehicle_license_plate: vehicleRes.data.license_plate,
        vehicle_model: vehicleRes.data.model
      };
    });
    const enhancedOrders = await Promise.all(orderPromises);
    allUserOrders.value = enhancedOrders;
    viewAllOrdersDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('加载用户所有工单失败');
  }
};

const handleScoreSubmit = async (row) => {
  try {
    await commentAssignmentApi(row.assignment_id, row.editScore);
    ElMessage.success('评价成功');
    // 更新本地数据
    row.score = row.editScore;
  } catch (error) {
    ElMessage.warning('评分失败');
    console.error('评分失败:', error);
  }
};

const REMIND_INTERVAL = 30 * 60 * 1000; // 30分钟（毫秒）

const handleRemindRecord = async (row) => {
  try {
    // 1. 查询当前任务的催单记录
    const res = await getRemindRecordApi(row.assignment_id);
    if (res?.data) {
      if (res.data.status == 0) {
        const lastRemindTime = new Date(res.data.reminder_time).getTime() || 0; // 上次催单时间（毫秒）
        const currentTime = Date.now();
        if (currentTime - lastRemindTime < REMIND_INTERVAL) {
          // 计算剩余等待时间（分钟）
          const remaining = Math.ceil((REMIND_INTERVAL - (currentTime - lastRemindTime)) / (1000 * 60));
          ElMessage.warning(`催促过于频繁，请${remaining}分钟后再试`);
          return;
        }

        if (res.data.reminder_count >= 3) {
          ElMessage.warning("您当前催单次数已达上限");
          return;
        }
      }
    }
    // 4. 执行催单（次数+1）
    await remindApi(row.assignment_id);
    ElMessage.success("催单成功，已为您加急处理");

  } catch (error) {
    ElMessage.warning(`催单失败：${error.response?.data?.message || '网络异常'}`);
    console.error('催单失败详情', error);
  }
};

const handleLogout = () => {
  localStorage.clear(); // 清空 localStorage
  router.push('/login'); // 跳转到登录页面
  ElMessage.success('已退出登录');
};

// 监听查询用户所有工单对话框显示状态变化，确保每次打开时重新获取数据
watch(viewAllOrdersDialogVisible, (newVal) => {
  if (newVal) {
    handleViewAllOrders();
  }
});

</script>

<style scoped>
.user-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}
</style>